package dfbz.com.service.impl;

import dfbz.com.dao.DeptDao;
import dfbz.com.model.Dept;
import dfbz.com.service.DeptService;

import java.util.*;

public class DeptServiceImpl implements DeptService {

    private DeptDao deptDao = new DeptDao();


    @Override
    public List<Dept> findAll() {
        return deptDao.findAll();
    }

    @Override
    public List<Map<String, Object>> findDeptList() {
        //数据库查出的所有数据（元数据）
        List<Map<String, Object>> all = deptDao.findList();

        //定义一个不能重复的部门ID集合
        Set<String> ids = new HashSet<>();

        //新的部门列表的集合
        List<Map<String, Object>> deptList = new ArrayList<>();
        Map<String, Object> deptMap;
        //遍历所有数据（元数据）
        for (Map<String, Object> map : all) {
            String deptId = map.get("deptId").toString();
            if (!ids.contains(deptId)) {
                //当不包含的情况下，才加进去
                deptMap = new HashMap<>();
                deptMap.put("deptId", deptId);
                deptMap.put("deptName", map.get("deptName"));
                deptMap.put("deptCount", 1);
                deptList.add(deptMap);
            } else {
                for (Map<String, Object> dept : deptList) {
                    if(deptId.equals(dept.get("deptId").toString())){
                        int count = Integer.parseInt(dept.get("deptCount").toString());
                        dept.put("deptCount",++count);
                        break;
                    }
                }
            }
            ids.add(deptId);
        }

        //给当前部门存放该部门下的所有员工
        List<Map<String,Object>> userList;
        Map<String,Object> userMap;

        for (Map<String,Object> dept : deptList) {
            String dId = dept.get("deptId").toString();
            userList = new ArrayList<>();
            //遍历数据，添加员工信息到userList集合里
            for (Map<String, Object> map : all) {
                String deptId = map.get("deptId").toString();
                if(deptId.equals(dId)){
                    userMap = new HashMap<>();
                    userMap.put("userId",map.get("userId"));
                    userMap.put("realName",map.get("realName"));
                    userList.add(userMap);
                }
            }
            dept.put("userList",userList);
        }

        System.out.println(deptList);
        return deptList;
    }

}

